package com.itheima.controller;

import com.itheima.pojo.Dept;
import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;

    //查询部门
    @RequestMapping(path="/depts", method = RequestMethod.GET)
    public Result deptList(){
        //调用业务层
        List<Dept> deptList = deptService.getDeptList();
        //业务逻辑校验
        if(deptList !=null&& deptList.size()>0){
            //查询结果合法，将结果返回给前端
            return Result.success(deptList);
        }

        return Result.error("查无数据");
    }

    //删除部门
    //@DeleteMapping("/depts/{id}")
    public Result delete(@PathVariable Integer id){
        //日志记录
        log.info("根据id删除部门");
        //调用service层功能
        deptService.delete(id);


        return Result.success();
    }

    //添加部门
    @PostMapping("/depts")
    public Result add(@RequestBody Dept dept){
        log.info("新增部门：{}",dept);
        //调用service层添加功能
        deptService.add(dept);
        return Result.success();


    }

    //通过id获取部门信息
    @GetMapping("/depts/{id}")
    public Result getId(@PathVariable Integer id){
        Dept dept = deptService.selectById(id);

        if (dept!=null){
            return Result.success(dept);
        }
        return Result.error("根据id获取出错");
    }
    //修改部门名称
    @PutMapping("/depts")
    public Result update(@RequestBody Dept dept ){

        deptService.update(dept);
        return Result.success();


    }

    @DeleteMapping("/depts/{id}")
    public Result deleteDeptById(@PathVariable Integer id){
        log.info("删除部门:{}",id);
        deptService.deleteEmpById(id);
        return Result.success();
    }
}
